package com.ics.atable.chat.config;

import org.springframework.ai.document.MetadataMode;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.openai.OpenAiEmbeddingOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.context.annotation.Primary;

/**
 * Embedding Model 配置类
 * <p>
 *  为了避免与 Spring Boot 自动配置冲突，建议在 application.yml 中设置： <pre>
 *  spring:
 *     ai:
 *       openai:
 *         embedding:
 *           enabled: false  # 禁用 OpenAI EmbeddingModel 自动配置
 *   </pre>
 *
 * @author haohongbin
 */
@Configuration
public class EmbeddingModelConfiguration {

    @Value("${spring.ai.openai.api-key}")
    private String apiKey;

    @Value("${spring.ai.openai.embedding.base-url}")
    private String baseUrl;

    @Value("${spring.ai.openai.embedding.options.model}")
    private String model;

    @Value("${spring.ai.openai.embedding.options.dimensions}")
    private Integer dimensions;

    @Bean("bgeM3EmbeddingModel")
    @Primary
    @ConditionalOnProperty(name = "spring.ai.openai.embedding.api-key")
    @ConditionalOnMissingBean(EmbeddingModel.class)
    public EmbeddingModel bgeMeEmbeddingModel() {
        OpenAiApi openAiApi = OpenAiApi.builder().apiKey(apiKey).baseUrl(baseUrl).build();
        return new OpenAiEmbeddingModel(
                openAiApi,
                MetadataMode.EMBED,
                OpenAiEmbeddingOptions.builder()
                        .model(model)
                        .dimensions(dimensions)
                        .build());
    }
}
